package net.aramzamzam.tapestry.judo.mixins;

import net.aramzamzam.tapestry.judo.services.WidgetService;

import org.apache.tapestry5.BindingConstants;
import org.apache.tapestry5.ClientElement;
import org.apache.tapestry5.ComponentResources;
import org.apache.tapestry5.MarkupWriter;
import org.apache.tapestry5.MarkupWriterListener;
import org.apache.tapestry5.annotations.Environmental;
import org.apache.tapestry5.annotations.InjectContainer;
import org.apache.tapestry5.annotations.Parameter;
import org.apache.tapestry5.annotations.SupportsInformalParameters;
import org.apache.tapestry5.dom.Element;
import org.apache.tapestry5.ioc.annotations.Inject;


/**
 * Generic dojo widget coponent
 * 	example:
 * 		<div t:type="dojo/generic" t:dojoType="TitlePane" t:title="title"></div>
 * @author solomenchuk
 *
 */
@SupportsInformalParameters
public class Widget{
	@Parameter(defaultPrefix = BindingConstants.LITERAL)
	private String dojoModule;
	
	@Parameter(required=true, defaultPrefix = BindingConstants.LITERAL)
	private String dojoType;
	
	@Inject
    private ComponentResources resources;
	
	@Environmental
	private WidgetService pageRenderSupport;
	
	@InjectContainer
	private ClientElement clientElement;
	
	private Element componentRoot;
	
	//FIXME how to obtain root element?
	void beginRender(final MarkupWriter writer)
    {
		componentRoot=null;
		writer.addListener(new MarkupWriterListener(){
			@Override
			public void elementDidEnd(Element element) {
			}
			@Override
			public void elementDidStart(Element element) {
				componentRoot=element;
				writer.removeListener(this);
			}
		});
    }
	
	/** Ends the element. */
    void afterRender(MarkupWriter writer)
    {
    	if (componentRoot!=null)
    	{
    		String id = clientElement.getClientId();
    		componentRoot.attribute("id", id);
    		pageRenderSupport.createWidget(dojoType, dojoModule, componentRoot, resources);
    	}
    }

}
